<?php

namespace app\api\logic;

use app\basic\model\UserThird;
use EasyWeChat\Factory;
use app\admin\logic\system\SystemConfigLogic;

class MiniAppWechat
{
    protected $app;

    protected $error;

    protected $model;

    /**
     * 初始化
     */
    public function __construct()
    {
        $logic = new SystemConfigLogic();
        $miniappConfig = $logic->getConfig('miniapp')['value'];
        $config = [
            'app_id' => $miniappConfig['app_id'],
            'secret' => $miniappConfig['app_secret'],
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => runtime_path().'/wechat.log',
            ],
        ];
        $this->app = Factory::miniProgram($config);
        $this->model = new UserThird();
    }

    /**
     * 微信小程序登录
     */
    public function miniAppLogin($code,$encryptedData,$iv)
    {
        $result = $this->app->auth->session($code);
        // 获取参数 session_key 和 openid
        if(isset($result['errcode'])){
            $this->error = $result['errmsg'];
            return false;
        }
        // 将 openID 入库到数据库保存
        $decryptedData = $this->app->encryptor->decryptData($result['session_key'], $iv, $encryptedData);
        $result['unionid'] = isset($result['unionid'])?$result['unionid']:'';
        $is_exist_third_info = $this->model->where('type', $this->model::TYPE_LIST['mini'])
            ->where('openid', $result['openid'])
            ->where('unionid', $result['unionid'])
            ->field('id,user_id')
            ->find();
        $phone = $decryptedData['purePhoneNumber'];
        $formatted_phone = substr($phone, 0, 3) . '****' . substr($phone, -4);
        $mini_username = $this->model::TYPE_MAP_LIST[$this->model::TYPE_LIST['mini']] . "_" . $formatted_phone;
        $user_data = [
            'username' => $mini_username,
            'password' => '',
            'email' => '',
            'user_id' => '0',
            'mobile' => $decryptedData['purePhoneNumber'],
            'type' => $this->model::TYPE_LIST['mini'],
            'unionid' => $result['unionid'],
            'session_key' => $result['session_key'],
            'openid' => $result['openid'],
        ];
        if ($is_exist_third_info) {
             $user_data['user_id'] = $is_exist_third_info['user_id'];
        }
        return $user_data;
    }

    /**
     * 获取小程序的信息
     */
    public function getSession($code)
    {
        $result = $this->app->auth->session($code);
        // 获取参数 session_key 和 openid
        if(isset($result['errcode'])){
            $this->error = $result['errmsg'];
            return false;
        }
        $result['unionid'] = isset($result['unionid'])?$result['unionid']:'';
        $is_exist_third_info = $this->model->where('type', $this->model::TYPE_LIST['mini'])
            ->where('openid', $result['openid'])
            ->where('unionid', $result['unionid'])
            ->field('id,user_id')
            ->find();
        if ($is_exist_third_info) {
            $result['user_id'] = $is_exist_third_info['user_id'];
        }
        return $result;
    }
    /**
     * 保存三方信息
     * @param $data
     * @param $result
     */
    public function setUserThird($data,$result)
    {
       $result['user_id'] = $data['id'];
       return $this->model->allowField(['user_id','type','unionid','session_key','openid'])->save($result);
    }
    public function setError($error)
    {
        $this->error = $error;
    }

    public function getError()
    {
        return $this->error;
    }



}